﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PaddleOCRSharp;

namespace PaddleOcr
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            dataGridViewMain.RowHeadersVisible = false;  //隐藏第一列空白
        }

        //选择文件
        private void button2_Click(object sender, EventArgs e)
        {
            int count = 1;

            //清空数据
            dataGridViewMain.Rows.Clear();

            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "图片文件(*.*)|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
            dialog.RestoreDirectory = true; //记忆上次打开的目录

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string[] strNames = dialog.SafeFileNames; //文件名列表（不带路径）
                for (int i = 0; i < strNames.Length; i++)
                {
                    //Path.GetDirectoryName(dialog.FileName)+strNames[i] 路径+文件名                    
                    string strlj = Path.GetDirectoryName(dialog.FileName) + "\\" + strNames[i];//文件全路径
                    var size = new FileInfo(strlj).Length / 1024 + "k";//文件大小
                    int index = this.dataGridViewMain.Rows.Add();
                    this.dataGridViewMain.Rows[index].Cells[0].Value = count++; //序号
                    this.dataGridViewMain.Rows[index].Cells[1].Value = strlj;
                    this.dataGridViewMain.Rows[index].Cells[2].Value = size;
                }
            }
        }


        //识别方法
        private void button1_Click(object sender, EventArgs e)
        {
            //数据初始化
            int TotalCount;     //总行数
            int Percent = 0;    //百分比
            TotalCount = dataGridViewMain.Rows.Count - 1;
            barStatus.Visible = true;

            for (int ii = 0; ii < TotalCount; ii++)
            {
                var obfile = dataGridViewMain.Rows[ii].Cells[1].Value;
                var imagebyte = File.ReadAllBytes(obfile.ToString());
                Bitmap bitmap = new Bitmap(new MemoryStream(imagebyte));

                OCRModelConfig config = null;
                OCRParameter oCRParameter = new OCRParameter();
                //oCRParameter.use_gpu=1;当使用GPU版本的预测库时，该参数打开才有效果
                //oCRParameter.Enable_mkldnn = 0; //关闭 CPU 加速参数  net项目中注意识别完后的图像内存清理
                OCRResult ocrResult = new OCRResult();
                using (PaddleOCREngine engine = new PaddleOCREngine(config, oCRParameter))
                {
                    ocrResult = engine.DetectText(bitmap);
                    //进度条
                    Percent = (int)(100 * (ii + 1) / TotalCount);
                    barStatus.Maximum = TotalCount;
                    barStatus.Value = ii + 1;
                    lbpercent.Text = Percent + "%";
                    Application.DoEvents();

                }
                if (ocrResult != null)
                {
                    //判断关键字
                    if (gjz.Text != "")
                    {
                        //循环结果words
                        for (int i = 0; i < ocrResult.TextBlocks.Count; i++)
                        {
                            //判断关键字
                            if (ocrResult.TextBlocks[i].Text.Contains(gjz.Text))
                            {
                                dataGridViewMain.Rows[ii].Cells[3].Value = ocrResult.TextBlocks[i].Text;
                                break;
                            }
                            else {
                                dataGridViewMain.Rows[ii].Cells[3].Value = "不含【"+gjz.Text+"】重新换个关键字再识别。。。";
                            }
                        }
                    }
                    else
                    {
                        //循环结果words
                        for (int i = 0; i < ocrResult.TextBlocks.Count; i++)
                        {
                            //全部结果
                            dataGridViewMain.Rows[ii].Cells[3].Value = ocrResult.Text;
                        }
                    }

                }

            }
        }


        //导出结果
        private void button3_Click(object sender, EventArgs e)
        {
            DownloadDataGridView(dataGridViewMain);
        }


        //导出结果方法DownloadDataGridView
        public void DownloadDataGridView(DataGridView dgv)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "Execl files (*.xlsx)|*.xlsx",
                FilterIndex = 0,
                RestoreDirectory = true,
                CreatePrompt = true,
                Title = "导出到Excel",
                FileName = "结果" + DateTime.Now.ToString("yyyMMddHHmmss") //结果表名称
            };
            saveFileDialog.ShowDialog();
            if (saveFileDialog.FileName == "")
            {
                return;
            }//end if          
             //数据初始化
            int TotalCount;     //总行数
            int Percent = 0;    //百分比
            TotalCount = dgv.Rows.Count - 1;
            barStatus.Visible = true;

            Stream myStream = saveFileDialog.OpenFile();
            //使用默认编码
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string str = "";
            try
            {
                for (int i = 0; i < dgv.ColumnCount; i++)
                {
                    str += dgv.Columns[i].HeaderText;
                    str += "\t";
                }//end for
                sw.WriteLine(str);
                for (int j = 0; j < dgv.Rows.Count - 1; j++)
                {
                    string strTemp = "";
                    for (int k = 0; k < dgv.Columns.Count; k++)
                    {
                        object obj = dgv.Rows[j].Cells[k].Value;
                        if (obj != null)
                        {
                            strTemp += dgv.Rows[j].Cells[k].Value.ToString();
                        }//end if
                        else
                        {
                            strTemp = "";
                        }//end else
                        strTemp += "\t";
                    }//end for k

                    Percent = (int)(100 * j / TotalCount);
                    barStatus.Maximum = TotalCount;
                    barStatus.Value = j + 1;
                    Application.DoEvents();

                    sw.WriteLine(strTemp);
                }//end for j

                sw.Close();
                myStream.Close();

                //成功提示
                if (MessageBox.Show("导出成功，是否立即打开？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(saveFileDialog.FileName);
                }

                //进度条赋初始值            
                barStatus.Value = 0;

            }//end try
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }//end catch
            finally
            {
                sw.Close();
                myStream.Close();
                lbpercent.Text = "";
            }//end finally           

        }

    }
}

